# -*- coding: utf-8 -*-

"http://hq.sinajs.cn/?format=text&list=AUDUSD,DINIW,EURUSD,GBPUSD,NZDUSD,USDCAD,USDCHF,USDCNY,USDHKD,USDJPY,USDMYR,USDSGD,USDTWD"

import requests
import time
import datetime
import re
from eventEngine import *
"""行情获取基类"""

FUNCTIONCODE_GETMARKET = 0

class HttpAPI(object):
    DEBUG = False
    def __init__(self):
        self.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Accept-Language': 'zh-CN,zh;q=0.8',
            'Connection': 'keep-alive',
            'Upgrade - Insecure - Requests': '1',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.100 Safari/537.36'
        }
        self.restDomain="http://hq.sinajs.cn"
        self.session = None
        self.functionSetting = {}
        self.active = False  # API的工作状态
        self.reqID = 0  # 请求编号
        self.reqQueue = Queue()  # 请求队列
        self.reqThread = Thread(target=self.processQueue)  # 请求处理线程
        self.init()

    def init(self):
         self.session = requests.Session()
         self.initFunctionSetting(FUNCTIONCODE_GETMARKET, {'path': '/?format=text&list=AUDUSD,DINIW,EURUSD,GBPUSD,NZDUSD,USDCAD,USDCHF,USDCNY,USDHKD,USDJPY,USDMYR,USDSGD,USDTWD',                                                             'method': 'GET'})
         self.active = True
         self.reqThread.start()

    def initFunctionSetting(self, code, setting):
        """初始化API功能字典"""
        self.functionSetting[code] = setting

    def exit(self):
        """退出接口"""
        if self.active:
            self.active = False
            self.reqThread.join()
    # ----------------------------------------------------------------------
    def processRequest(self, req):
            """发送请求并通过回调函数推送数据结果"""
            url = req['url']
            method = req['method']
            params = req['params']

            stream = False
            if 'stream' in req:
                stream = req['stream']

            if method in ['GET', 'DELETE']:
                myreq = requests.Request(method, url, headers=self.headers, params=params)
            elif method in ['POST', 'PATCH']:
                myreq = requests.Request(method, url, headers=self.headers, data=params)
            pre = myreq.prepare()

            r = None
            error = None

            try:
                r = self.session.send(pre, stream=stream)
            except Exception, e:
                error = e

            return r, error
            # ----------------------------------------------------------------------

    def processQueue(self):
        """处理请求队列中的请求"""
        while self.active:
            try:
                req = self.reqQueue.get(block=True, timeout=1)  # 获取请求的阻塞为一秒
                callback = req['callback']
                reqID = req['reqID']

                r, error = self.processRequest(req)

                if r:
                    try:
                        data = r.text
                        if self.DEBUG:
                            print callback.__name__
                        callback(data, reqID)
                    except Exception, e:
                        self.onError(str(e), reqID)
                else:
                    self.onError(error, reqID)
            except Empty:
                pass


    def sendRequest(self, code, params, callback, optional=''):
        """发送请求"""
        setting = self.functionSetting[code]
        url = self.restDomain + setting['path']
        if optional:
            url = url + '/' + optional
        self.reqID += 1
        req = {'url': url,
               'method': setting['method'],
               'params': params,
               'callback': callback,
               'reqID': self.reqID}
        self.reqQueue.put(req)
        return self.reqID

    def getMarketData(self, params=None):
        """查询行情"""
        return self.sendRequest(FUNCTIONCODE_GETMARKET, params, self.onRtnDepthMarketData)

    def onError(self, error, reqID):
        """错误信息回调"""
        print error, reqID


    def onRtnDepthMarketData(self , data, reqID):
        if self.DEBUG:
            print data



if __name__ == '__main__':
    api = HttpAPI()
    api.DEBUG = True
    api.getMarketData()

